<template>
  <div id="add_chat">
    <div class="group_content">
      <!-- 标题部分 -->
      <div class="header">
        <div class="left" @click="$router.back()">
          <i class="el-icon-arrow-left"></i>
        </div>
        <div class="group_name">{{ title }}</div>
        <div class="right"></div>
      </div>
      <div class="inner">
        <div class="title">添加好友 / 群聊</div>
        <!-- 搜索部分-->
        <div class="search">
          <!-- 提示部分 -->
          <div class="text">
            您可以通过输入昵称的方式来精确搜索用户/群聊，然后点击添加好友/群聊
          </div>
          <!-- 搜索框部分 -->
          <div class="input" ref="input">
            <input
              type="text"
              v-model="input"
              placeholder="用户名 / 群聊名"
              @focus="$refs.input.style = 'border:1px solid #00aff4'"
              @blur="$refs.input.style = ''"
            />
            <div
              class="button_n"
              :class="input == '' ? '' : 'button'"
              @click="clickSearch"
            >
              点击搜索
            </div>
          </div>
        </div>
      </div>
      <!-- 主体内容部分 -->
      <div class="content">
        <!-- 控制栏部分 -->
        <div class="switch">
          <div
            class="users_result"
            :class="type == 1 ? 'active' : ''"
            @click="type = 1"
          >
            找人
          </div>
          <div
            class="groups_result"
            :class="type == 2 ? 'active' : ''"
            @click="type = 2"
          >
            找群
          </div>
        </div>
        <!-- 创建群 -->
        <div class="creating">
          <!-- Form -->
          <el-button type="text" @click="dialogFormVisible = true">
            没找到群聊？赶紧来创建一个吧！
          </el-button>
          <!-- 弹出框 -->
          <el-dialog
            title="创建群聊"
            :visible.sync="dialogFormVisible"
            ref="dialog"
          >
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
            >
              <el-form-item label="群名称：" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
              </el-form-item>
              <el-form-item
                label="群头像："
                ref="uploadElement"
                prop="imageUrl"
                class="uploadAvatar"
              >
                <el-input v-model="ruleForm.imageUrl" v-if="false"></el-input>
                <el-upload
                  class="avatar-uploader"
                  ref="upload"
                  list-type="picture-card"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :show-file-list="true"
                  action="/index/upload"
                  :before-upload="beforeUpload"
                  :auto-upload="false"
                  :data="ruleForm"
                  :limit="1"
                >
                  <i
                    v-if="addPic"
                    class="el-icon-plus avatar-uploader-icon"
                  ></i>
                </el-upload>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="clear">清空</el-button>
              <el-button type="primary" @click="createNewGroup">
                创建
              </el-button>
            </div>
          </el-dialog>
        </div>
        <div class="content_title">
          搜索结果：<span v-if="type==1">{{resultUsers.length}}</span>
          <span v-if="type==2">{{resultGroups.length}}</span>
        </div>
        <!-- 这是好友的 -->
        <div class="result" v-if="type == 1">
          <div
            class="item"
            v-for="(item, index) in resultUsers"
            :key="index"
            tabindex="-1"
          >
            <div class="avatar">
              <img :src="$host + item.avatar" />
            </div>
            <div class="name" v-html="item.userInfos[0].nickName"></div>
            <div class="id">账号: {{ item.username }}</div>
            <div class="bottom" :plain="true">
              <svg class="icon" aria-hidden="true" @click="addFriends(item.id)">
                <use xlink:href="#icon-tianjia-copy"></use>
              </svg>
            </div>
          </div>
        </div>
        <!-- 这是群聊的 -->
        <div class="result" v-if="type == 2">
          <div
            class="item"
            v-for="(item, index) in resultGroups"
            :key="index"
            tabindex="-1"
          >
            <div class="avatar">
              <img :src="$host + item.groupImg" />
            </div>
            <div class="name" v-html="item.groupName"></div>
            <div class="id">id: {{ item.groupId }}</div>
            <div class="number">群成员: {{ item.count }}/500</div>
            <div class="bottom">
              <svg
                class="icon"
                aria-hidden="true"
                @click="joinGroup(item.groupId)"
              >
                <use xlink:href="#icon-tianjia-copy"></use>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 右边展示框 -->
    <div class="group_details"></div>
  </div>
</template>

<script>
  import { createNewGroup, getGroupInfo, getUserByNick, joinGroup, addFriends } from '@/utils/chatBox'

  export default {
    name: 'AddChat',
    data() {
      return {
        dialogFormVisible: false,     //是否显示创建群聊弹出框
        addPic: true,                //是否显示添加群头像框
        ruleForm: {
          name: '',
          imageUrl: '',
        },
        formData: new FormData(),  //自定义表单提交数据
        isLt5M: true,
        //表单验证规则
        rules: {
          name: [{ validator: this.checkName, trigger: 'blur' }],
        },
        title: '加载中',
        input: '',          //搜索框内容
        resultUsers: [],    //搜索到的所有用户
        resultGroups: [],   //搜索到的所有群聊
        allGroups: [],      //全部群聊
        type: 1,            //选择框样式控制
      }
    },
    methods: {
      // 这是创建群聊ele组件的函数
      beforeUpload(file) {
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.isLt2M = false
          return false;
        }
        this.formData.append('avatar', file)
        return false;
      },
      handleChange() {
        this.addPic = false
      },
      //移除图片后的回调
      handleRemove() {
        //等一秒动画
        setTimeout(() => { this.addPic = true }, 1100)
      },
      clear() {
        this.ruleForm = {
          name: '',
          imageUrl: ''
        }
        // 让图片提交,继而让它消失
        this.$refs.upload.submit();
      },
      //这是群聊名称验证规则
      checkName(rule, value, callback) {
        let Regex = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
        if (!Regex.test(value)) {
          return callback(new Error('群名不合法:请输入中文 / 英文 / 数字'));
        }
      },
      //创建群聊  ajax  加图片大小判断
      async createNewGroup() {
        let Regex = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
        //如果群名不合法
        if (Regex.test(this.ruleForm.name)) {
          //手动触发ele组件的upload
          this.$refs.upload.submit();
          //如果图片大于5M,报错并返回
          if (!this.isLt5M) {
            this.$message.error('上传头像图片大小不能超过 5MB!');
            return
          }
          //如果图片小于5M,则函数继续执行
          let userId = JSON.parse(localStorage.getItem('user')).qaqUser.id
          this.formData.append("groupName", this.ruleForm.name)
          await createNewGroup(userId, this.formData).then(response => {

            if (response.data.code) {
              this.$message.success(response.data.data);
              this.dialogFormVisible = false
              this.clear()
            } else {
              this.$message.warning(response.data.msg);
            }
          }).catch(() => {
            this.$message.error('创建失败！请检查信息是否完全');
          })
          //实时更新用户群数据
          this.$store.dispatch('getMyGroup')
        } else {
          this.$message.error('群名不合法:请输入中文 / 英文 / 数字');
        }
      },

      //模糊搜索群聊
      async getGroupInfo() {
        let { data: { data } } = await getGroupInfo(this.input)
        this.resultGroups = []
        if (data[0] !== null) {
          //搜索关键字标红
          this.resultGroups = data.map((item) => {
            item.groupName = item.groupName.replace(this.input, `<span style="color:red">${this.input}</span>`)
            return item
          })
        }
      },
      //模糊搜索用户
      async getUserByNick() {
        let { data: { data } } = await getUserByNick(this.input)
        this.resultUsers = []
        if (data.length !== 0) {
          //搜索关键字标红
          this.resultUsers = data.map((item) => {
            item.userInfos[0].nickName = item.userInfos[0].nickName.replace(this.input, `<span style="color:red">${this.input}</span>`)
            return item
          })
        }
      },
      // 添加群
      async joinGroup(groupId) {
        let userId = JSON.parse(localStorage.getItem('user')).qaqUser.id
        await joinGroup(groupId, userId).then(response => {
          if (response.data.code) {
            this.$message({
              message: response.data.msg,
              type: 'success'
            })
            //调用vuex,实现实时更新用户群聊数据
            this.$store.dispatch('getMyGroup')
          } else {
            this.$message({
              message: response.data.msg,
              type: 'warning'
            })
          }
        })
      },
      //添加好友
      async addFriends(friendId) {
        let myId = JSON.parse(localStorage.getItem('user')).qaqUser.id
        await addFriends(friendId, myId).then(response => {
          if (response.data.code) {
            this.$message({
              message: response.data.msg,
              type: 'success'
            })
            //调用vuex,实现实时更新用户好友数据
            this.$store.dispatch('getMyFriends')
          } else {
            this.$message({
              message: response.data.msg,
              type: 'warning'
            })
          }
        })
      },
      //点击搜索事件
      clickSearch() {
        // 根据input的值来获取搜索结果
        if (this.input.trim() !== '') {
          this.getGroupInfo()
          this.getUserByNick()
        }
      },
    },
    created() {
      this.title = '搜索页'
    },
  }
</script>

<style scoped>
  #add_chat {
    flex: 1;
    display: flex;
    height: 100vh;
  }

  .group_content {
    flex: 1;
    display: flex;
    flex-direction: column;
    /* justify-content: space-between; */
    background-color: #36393f;
    overflow: hidden;
  }

  /* 标题部分 */
  .group_content .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 48px;
    box-shadow: 0 1px 0 rgba(4, 4, 5, 0.2), 0 1.5px 0 rgba(6, 6, 7, 0.05),
      0 2px 0 rgba(4, 4, 5, 0.05);
  }

  .header .left,
  .header .right {
    width: 48px;
    height: 48px;
    text-align: center;
    font-size: 24px;
    line-height: 48px;
    color: #fff;
    cursor: pointer;
  }

  .header .group_name {
    flex: 1;
    text-align: center;
    font-weight: 800;
    color: #fff;
  }

  /* 提示栏栏部分 */
  .inner {
    box-sizing: content-box;
    padding: 20px 30px;
    height: 126px;
    border-bottom: 1px solid #42454a;
  }

  .inner .title {
    height: 20px;
    margin-bottom: 16px;
    font-size: 16px;
    line-height: 20px;
    font-weight: 600;
    text-transform: uppercase;
    color: #ffffff;
  }

  .search .text {
    height: 20px;
    font-size: 12px;
    color: #a5a7ab;
  }

  /* 搜索框部分 */
  .search .input {
    display: flex;
    align-items: center;
    margin: 0 auto;
    margin-top: 16px;
    width: 100%;
    height: 54px;
    border: 1px solid #222428;
    border-radius: 8px;
    padding: 0 16px;
    background-color: #303339;
  }

  .search .input input {
    flex: 1;
    margin-right: 16px;
    padding: 16px 0;
    border: none;
    box-sizing: border-box;
    font-size: 16px;
    font-weight: 500;
    letter-spacing: 0.04em;
    line-height: 20px;
    white-space: pre;
    background-color: transparent;
    color: #dcddde;
  }

  .search .input .button_n {
    width: 152px;
    height: 32px;
    padding: 2px 16px;
    border-radius: 5px;
    font-size: 14px;
    text-align: center;
    line-height: 26px;
    background-color: #444c95;
    color: #97999b;
  }

  .search .input .button {
    background-color: #5865f2;
    color: #fefeff;
  }

  /* 内容部分 */
  .content {
    position: relative;
    flex: 1;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 215px);
    padding: 20px 30px;
  }

  .content .content_title {
    height: 20px;
    margin-top: 16px;
    font-size: 15px;
    line-height: 20px;
    font-weight: 600;
    text-transform: uppercase;
    color: #ffffff;
  }

  .content .switch {
    display: flex;
    width: 260px;
    height: 48px;
    overflow: hidden;
    border-radius: 5px;
  }

  /* 内容部分里的切换栏 */
  .content .switch .users_result,
  .content .switch .groups_result {
    position: relative;
    width: 100px;
    text-align: center;
    line-height: 48px;
    color: #fff;
    cursor: pointer;
    transition: width 0.3s ease-out;
  }

  .content .switch .users_result {
    background-color: #949cf7;
  }

  .content .switch .groups_result {
    background-color: #5865f2;
  }

  /* 被选中的样式 */
  .content .switch .active {
    width: 160px;
    z-index: 10;
    box-shadow: 2px 0px 2px rgba(43, 29, 29, 0.5),
      -2px 0px 2px rgba(43, 29, 29, 0.5);
  }

  /* 内容部分里的结果展示栏 */
  .content .result {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-content: start;
    margin-top: 5px;
    padding: 10px;
    border-radius: 5px;
    background-color: #2c2e33;
    overflow: auto;
  }

  /* 滚动条样式修改 */
  .result::-webkit-scrollbar {
    width: 6px;
    /* height: 4px; */
  }

  .result::-webkit-scrollbar-thumb {
    border: 5px solid;
    border-radius: 10px;
    background: #000;
  }

  .result .item {
    position: relative;
    width: 269px;
    margin: 6px 6px 0 0;
    height: 100px;
    background-color: #393c43;
  }

  .item .avatar {
    width: 48px;
    height: 48px;
    margin: 10px;
    border-radius: 50%;
    overflow: hidden;
  }

  .item .avatar img {
    width: 100%;
    height: 100%;
  }

  .item .name {
    position: absolute;
    top: 0;
    left: 68px;
    width: 200px;
    height: 20px;
    margin-top: 10px;
    font-size: 14px;
    color: #fff;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .item .id {
    position: absolute;
    top: 35px;
    left: 68px;
    width: 60px;
    height: 20px;
    font-size: 12px;
    color: #ccc;
    overflow: hidden;
    white-space: nowrap;
  }

  .item .number {
    position: absolute;
    top: 35px;
    left: 128px;
    width: 120px;
    height: 20px;
    font-size: 12px;
    color: #ccc;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .item .bottom {
    position: relative;
    height: 32px;
    border-radius: 10px 10px 0 0;
    /* background-color: #fca41c; */
    /* background-color: #ccc; */
    background-color: #6e707f;
    transition: all 0.3s ease;
  }

  .item:focus .bottom {
    border-radius: 50px 10px 0 0;
  }

  .item .bottom svg {
    position: absolute;
    right: 10px;
    font-size: 32px;
    cursor: pointer;
  }

  /* 这是创建群聊的 */
  input[type="file"] {
    display: none;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader /deep/ .el-upload--picture-card {
    border: 0;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    border: 1px dashed #c0ccda;
    border-radius: 4px;
    line-height: 148px;
    text-align: center;
  }
  .uploadAvatar {
    height: 155px;
  }
  .creating {
    position: absolute;
    display: flex;
    align-items: center;
    right: 30px;
    height: 48px;
  }
  .creating /deep/ .el-dialog {
    width: 35vw;
    background-color: #36393f;
  }
  .creating /deep/ .el-dialog__title {
    margin-left: 220px;
    font-weight: 500;
    color: #fff;
  }
  .creating /deep/ .el-form-item__content .el-input__inner {
    width: 80%;
    background-color: #2c2e33;
    border-color: transparent;
    color: #757575;
  }
  .creating /deep/ .el-upload--picture-card {
    width: auto;
    height: auto;
    background-color: #36393f;
  }
  .creating /deep/ .el-form-item__label {
    color: #757575;
  }
  /* 右边群展示框 */
  .group_details {
    width: 312px;
    background-color: #2f3136;
  }
</style>